<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="robots" content="noodp" />
        <title>1.3-多线程控制的另一种姿势-条件变量(condition_variable), 信号量(semaphore) - L_B__</title><meta name="referrer" content="no-referrer">
<meta name="description" content="1.3-多线程控制的另一种姿势-条件变量(condition_variable), 信号量(semaphore)"><meta property="og:title" content="1.3-多线程控制的另一种姿势-条件变量(condition_variable), 信号量(semaphore)" />
<meta property="og:description" content="1.3-多线程控制的另一种姿势-条件变量(condition_variable), 信号量(semaphore)" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://acking-you.github.io/posts/1.3-%E9%94%81%E9%87%8A%E6%94%BE%E7%9A%84%E5%8F%A6%E4%B8%80%E7%A7%8D%E5%A7%BF%E5%8A%BF-%E6%9D%A1%E4%BB%B6%E5%8F%98%E9%87%8Fcondition_variable-%E4%BF%A1%E5%8F%B7%E9%87%8Fsemaphore/" /><meta property="og:image" content="https://acking-you.github.io/logo.png"/><meta property="article:section" content="posts" />
<meta property="article:published_time" content="2022-03-27T00:00:00+00:00" />
<meta property="article:modified_time" content="2022-03-27T00:00:00+00:00" />

<meta name="twitter:card" content="summary_large_image"/>
<meta name="twitter:image" content="https://acking-you.github.io/logo.png"/>

<meta name="twitter:title" content="1.3-多线程控制的另一种姿势-条件变量(condition_variable), 信号量(semaphore)"/>
<meta name="twitter:description" content="1.3-多线程控制的另一种姿势-条件变量(condition_variable), 信号量(semaphore)"/>
<meta name="application-name" content="FeelIt">
<meta name="apple-mobile-web-app-title" content="FeelIt"><meta name="theme-color" content="#ffffff"><meta name="msapplication-TileColor" content="#da532c"><link rel="canonical" href="https://acking-you.github.io/posts/1.3-%E9%94%81%E9%87%8A%E6%94%BE%E7%9A%84%E5%8F%A6%E4%B8%80%E7%A7%8D%E5%A7%BF%E5%8A%BF-%E6%9D%A1%E4%BB%B6%E5%8F%98%E9%87%8Fcondition_variable-%E4%BF%A1%E5%8F%B7%E9%87%8Fsemaphore/" /><link rel="prev" href="https://acking-you.github.io/posts/%E5%88%A9%E7%94%A8string_view%E4%BC%98%E5%8C%96%E7%8E%B0%E4%BB%A3c&#43;&#43;%E8%AF%AD%E6%B3%95/" /><link rel="next" href="https://acking-you.github.io/posts/%E5%AE%9E%E7%8E%B0%E5%AE%9E%E6%97%B6qq%E5%A5%BD%E5%8F%8B%E6%90%9C%E7%B4%A2%E6%A1%86/" /><link rel="stylesheet" href="/css/page.min.css"><link rel="stylesheet" href="/css/home.min.css"><script type="application/ld+json">
    {
        "@context": "http://schema.org",
        "@type": "BlogPosting",
        "headline": "1.3-多线程控制的另一种姿势-条件变量(condition_variable), 信号量(semaphore)",
        "inLanguage": "zh-CN",
        "mainEntityOfPage": {
            "@type": "WebPage",
            "@id": "https:\/\/acking-you.github.io\/posts\/1.3-%E9%94%81%E9%87%8A%E6%94%BE%E7%9A%84%E5%8F%A6%E4%B8%80%E7%A7%8D%E5%A7%BF%E5%8A%BF-%E6%9D%A1%E4%BB%B6%E5%8F%98%E9%87%8Fcondition_variable-%E4%BF%A1%E5%8F%B7%E9%87%8Fsemaphore\/"
        },"genre": "posts","keywords": "1.3-多线程控制的另一种姿势-条件变量(condition_variable), 信号量(semaphore)","wordcount":  2857 ,
        "url": "https:\/\/acking-you.github.io\/posts\/1.3-%E9%94%81%E9%87%8A%E6%94%BE%E7%9A%84%E5%8F%A6%E4%B8%80%E7%A7%8D%E5%A7%BF%E5%8A%BF-%E6%9D%A1%E4%BB%B6%E5%8F%98%E9%87%8Fcondition_variable-%E4%BF%A1%E5%8F%B7%E9%87%8Fsemaphore\/","datePublished": "2022-03-27T00:00:00+00:00","dateModified": "2022-03-27T00:00:00+00:00","publisher": {
            "@type": "Organization",
            "name": "作者"},"author": {
                "@type": "Person",
                "name": "作者"
            },"description": "1.3-多线程控制的另一种姿势-条件变量(condition_variable), 信号量(semaphore)"
    }
    </script></head><body data-header-desktop="auto" data-header-mobile="auto"><script>(window.localStorage && localStorage.getItem('theme') ? localStorage.getItem('theme') === 'dark' : ('auto' === 'auto' ? window.matchMedia('(prefers-color-scheme: dark)').matches : 'auto' === 'dark')) && document.body.setAttribute('theme', 'dark');</script>

        <div id="mask"></div><div class="wrapper"><header class="desktop" id="header-desktop">
    <div class="header-wrapper">
        <div class="header-title">
            <a href="/" title="L_B__">L_B__</a>
        </div>
        <div class="menu">
            <div class="menu-inner"><a class="menu-item" href="/posts/"> 文章 </a><a class="menu-item" href="/tags/"> 标签 </a><a class="menu-item" href="/categories/"> 分类 </a><span class="menu-item delimiter"></span><span class="menu-item search" id="search-desktop">
                        <input type="text" placeholder="搜索文章标题或内容..." id="search-input-desktop">
                        <a href="#" class="search-button search-toggle" id="search-toggle-desktop" title="搜索">
                            <i class="fas fa-search fa-fw"></i>
                        </a>
                        <a href="#" class="search-button search-clear" id="search-clear-desktop" title="清空">
                            <i class="fas fa-times-circle fa-fw"></i>
                        </a>
                        <span class="search-button search-loading" id="search-loading-desktop">
                            <i class="fas fa-spinner fa-fw fa-spin"></i>
                        </span>
                    </span><a href="javascript:void(0);" class="menu-item theme-switch" title="切换主题">
                    <i class="fas fa-adjust fa-fw"></i>
                </a>
            </div>
        </div>
    </div>
</header><header class="mobile" id="header-mobile">
    <div class="header-container">
        <div class="header-wrapper">
            <div class="header-title">
                <a href="/" title="L_B__">L_B__</a>
            </div>
            <div class="menu-toggle" id="menu-toggle-mobile">
                <span></span><span></span><span></span>
            </div>
        </div>
        <div class="menu" id="menu-mobile"><div class="search-wrapper">
                    <div class="search mobile" id="search-mobile">
                        <input type="text" placeholder="搜索文章标题或内容..." id="search-input-mobile">
                        <a href="#" class="search-button search-toggle" id="search-toggle-mobile" title="搜索">
                            <i class="fas fa-search fa-fw"></i>
                        </a>
                        <a href="#" class="search-button search-clear" id="search-clear-mobile" title="清空">
                            <i class="fas fa-times-circle fa-fw"></i>
                        </a>
                        <span class="search-button search-loading" id="search-loading-mobile">
                            <i class="fas fa-spinner fa-fw fa-spin"></i>
                        </span>
                    </div>
                    <a href="#" class="search-cancel" id="search-cancel-mobile">
                        取消
                    </a>
                </div><a class="menu-item" href="/posts/" title="">文章</a><a class="menu-item" href="/tags/" title="">标签</a><a class="menu-item" href="/categories/" title="">分类</a><div class="menu-item"><a href="javascript:void(0);" class="theme-switch" title="切换主题">
                    <i class="fas fa-adjust fa-fw"></i>
                </a>
            </div></div>
    </div>
</header><div class="search-dropdown desktop">
    <div id="search-dropdown-desktop"></div>
</div>
<div class="search-dropdown mobile">
    <div id="search-dropdown-mobile"></div>
</div><main class="main">
                <div class="container"><div class="toc" id="toc-auto">
            <h2 class="toc-title">目录</h2>
            <div class="toc-content" id="toc-content-auto"></div>
        </div><article class="page single" data-toc="disable"><div class="featured-image"><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://img-blog.csdnimg.cn/img_convert/385f4cc39feda8590ef42f86b38207ba.png#pic_center"
        data-srcset="https://img-blog.csdnimg.cn/img_convert/385f4cc39feda8590ef42f86b38207ba.png#pic_center, https://img-blog.csdnimg.cn/img_convert/385f4cc39feda8590ef42f86b38207ba.png#pic_center 1.5x, https://img-blog.csdnimg.cn/img_convert/385f4cc39feda8590ef42f86b38207ba.png#pic_center 2x"
        data-sizes="auto"
        alt="https://img-blog.csdnimg.cn/img_convert/385f4cc39feda8590ef42f86b38207ba.png#pic_center"
        title="1.3-多线程控制的另一种姿势-条件变量(condition_variable), 信号量(semaphore)" /></div><div class="single-card" data-image="true"><h2 class="single-title animated flipInX">1.3-多线程控制的另一种姿势-条件变量(condition_variable), 信号量(semaphore)</h2><div class="post-meta">
                <div class="post-meta-line"><span class="post-author"><a href="/" title="Author" rel=" author" class="author"><i class="fas fa-user-circle fa-fw"></i>作者</a></span>&nbsp;<span class="post-category">出版于  <a href="/categories/c++%E5%A4%9A%E7%BA%BF%E7%A8%8B/"><i class="far fa-folder fa-fw"></i>C++多线程</a></span></div>
                <div class="post-meta-line"><span><i class="far fa-calendar-alt fa-fw"></i>&nbsp;<time datetime="2022-03-27">2022-03-27</time></span>&nbsp;<span><i class="fas fa-pencil-alt fa-fw"></i>&nbsp;约 2857 字</span>&nbsp;
                    <span><i class="far fa-clock fa-fw"></i>&nbsp;预计阅读 6 分钟</span>&nbsp;</div>
            </div>
            
            <hr><div class="details toc" id="toc-static"  data-kept="">
                    <div class="details-summary toc-title">
                        <span>目录</span>
                        <span><i class="details-icon fas fa-angle-right"></i></span>
                    </div>
                    <div class="details-content toc-content" id="toc-content-static"><nav id="TableOfContents">
  <ul>
    <li><a href="#条件变量c11">条件变量(C++11)</a>
      <ul>
        <li><a href="#为什么要引入条件变量">为什么要引入条件变量</a></li>
        <li><a href="#条件变量的用法">条件变量的用法</a></li>
        <li><a href="#条件变量引发的虚假唤醒">条件变量引发的虚假唤醒</a></li>
      </ul>
    </li>
    <li><a href="#信号量c20">信号量(C++20)</a>
      <ul>
        <li><a href="#stdbinary_semaphore使用">std::binary_semaphore使用</a></li>
        <li><a href="#counting_semaphore使用">counting_semaphore使用</a></li>
      </ul>
    </li>
  </ul>
</nav></div>
                </div><div class="content" id="content"><h2 id="条件变量c11">条件变量(C++11)</h2>
<h3 id="为什么要引入条件变量">为什么要引入条件变量</h3>
<p>我们先来看看一个由互斥量加锁构成的生产者消费者模型：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-cpp" data-lang="cpp"><span class="c1">//
</span><span class="c1">// Created by Alone on 2022-3-27.
</span><span class="c1">//
</span><span class="c1"></span><span class="cp">#include</span> <span class="cpf">&lt;iostream&gt;</span><span class="cp">
</span><span class="cp">#include</span> <span class="cpf">&lt;mutex&gt;</span><span class="cp">
</span><span class="cp">#include</span> <span class="cpf">&lt;deque&gt;</span><span class="cp">
</span><span class="cp">#include</span> <span class="cpf">&lt;thread&gt;</span><span class="cp">
</span><span class="cp"></span><span class="n">std</span><span class="o">::</span><span class="n">mutex</span> <span class="n">mtx</span><span class="p">;</span>
<span class="n">std</span><span class="o">::</span><span class="n">deque</span><span class="o">&lt;</span><span class="kt">int</span><span class="o">&gt;</span> <span class="n">q</span><span class="p">;</span>

<span class="c1">// producer
</span><span class="c1"></span><span class="kt">void</span> <span class="nf">task1</span><span class="p">(){</span>
    <span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
    <span class="k">while</span> <span class="p">(</span><span class="mi">1</span><span class="p">){</span>
        <span class="n">std</span><span class="o">::</span><span class="n">unique_lock</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">mutex</span><span class="o">&gt;</span> <span class="n">lock</span><span class="p">(</span><span class="n">mtx</span><span class="p">);</span>
        <span class="c1">//std::this_thread::sleep_for(std::chrono::milliseconds(10));
</span><span class="c1"></span>        <span class="n">q</span><span class="p">.</span><span class="n">push_back</span><span class="p">(</span><span class="n">i</span><span class="p">);</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">i</span> <span class="o">&lt;</span> <span class="mi">9999999</span><span class="p">)</span> <span class="p">{</span>
            <span class="n">i</span><span class="o">++</span><span class="p">;</span>
        <span class="p">}</span><span class="k">else</span> <span class="p">{</span>
            <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="c1">// consumer
</span><span class="c1"></span><span class="kt">void</span> <span class="nf">task2</span><span class="p">(){</span>
    <span class="kt">int</span> <span class="n">data</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
    <span class="k">while</span> <span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">std</span><span class="o">::</span><span class="n">unique_lock</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">mutex</span><span class="o">&gt;</span> <span class="n">lock</span><span class="p">(</span><span class="n">mtx</span><span class="p">);</span>
        <span class="k">if</span><span class="p">(</span><span class="o">!</span><span class="n">q</span><span class="p">.</span><span class="n">empty</span><span class="p">()){</span>
            <span class="n">data</span> <span class="o">=</span> <span class="n">q</span><span class="p">.</span><span class="n">front</span><span class="p">();</span>
            <span class="n">q</span><span class="p">.</span><span class="n">pop_front</span><span class="p">();</span>
            <span class="n">std</span><span class="o">::</span><span class="n">cout</span><span class="o">&lt;&lt;</span><span class="s">&#34;Get value from que task2:&#34;</span><span class="o">&lt;&lt;</span><span class="n">data</span><span class="o">&lt;&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="kt">void</span> <span class="nf">task3</span><span class="p">(){</span>
    <span class="kt">int</span> <span class="n">data</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
    <span class="k">while</span> <span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">std</span><span class="o">::</span><span class="n">unique_lock</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">mutex</span><span class="o">&gt;</span> <span class="n">lock</span><span class="p">(</span><span class="n">mtx</span><span class="p">);</span>
        <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">q</span><span class="p">.</span><span class="n">empty</span><span class="p">())</span> <span class="p">{</span>
            <span class="n">data</span> <span class="o">=</span> <span class="n">q</span><span class="p">.</span><span class="n">front</span><span class="p">();</span>
            <span class="n">q</span><span class="p">.</span><span class="n">pop_front</span><span class="p">();</span>
            <span class="n">std</span><span class="o">::</span><span class="n">cout</span><span class="o">&lt;&lt;</span><span class="s">&#34;Get value from que task3:&#34;</span><span class="o">&lt;&lt;</span><span class="n">data</span><span class="o">&lt;&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>


<span class="kt">int</span> <span class="nf">main</span><span class="p">()</span> <span class="p">{</span>
    <span class="n">std</span><span class="o">::</span><span class="kr">thread</span> <span class="n">t1</span><span class="p">(</span><span class="n">task1</span><span class="p">);</span>
    <span class="n">std</span><span class="o">::</span><span class="kr">thread</span> <span class="n">t2</span><span class="p">(</span><span class="n">task2</span><span class="p">);</span>
    <span class="n">std</span><span class="o">::</span><span class="kr">thread</span> <span class="n">t3</span><span class="p">(</span><span class="n">task3</span><span class="p">);</span>
    <span class="n">t1</span><span class="p">.</span><span class="n">join</span><span class="p">();</span>
    <span class="n">t2</span><span class="p">.</span><span class="n">join</span><span class="p">();</span>
    <span class="n">t3</span><span class="p">.</span><span class="n">join</span><span class="p">();</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>

</code></pre></div><blockquote>
<p>以上代码，由于直接的while(1)循环会导致cpu资源占用的非常厉害，我们可以通过延时sleep_for来进行优化，但这个延时的时间我们并不好控制！</p>
</blockquote>
<p>我们这个生产者、消费者线程，想要实现的愿景就是，当生成者生产出资源后，我们能够及时的唤醒消费者线程，让其获取资源。</p>
<p>但如果是简单的对生产者和消费者进行加锁来实现这一过程，可能中间会有很多过程是在消费者拿到锁后，发现生产者并没有生产出资源，而这个过程很明显就是一个无用功，那么有没有一种方式能够让生产者生产出资源后，立马通知消费者线程来读取，且在没有资源的时候，消费者线程能够阻塞让出cpu时间片呢？实现这个需求有很多种方法，而条件变量就是其中的一种！</p>
<h3 id="条件变量的用法">条件变量的用法</h3>
<p>从C++11起，标准库开始引入条件变量。</p>
<p>它的成员函数也不复杂，就下面这些：</p>
<p><a href="https://cplusplus.com/reference/condition_variable/condition_variable/?kw=condition_variable" target="_blank" rel="noopener noreffer">更多详细描述</a></p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://img-blog.csdnimg.cn/7af8a31f83b84f788de290fc40aa0d0e.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAQytH,size_20,color_FFFFFF,t_70,g_se,x_16"
        data-srcset="https://img-blog.csdnimg.cn/7af8a31f83b84f788de290fc40aa0d0e.png?x-oss-process=image/watermark%2ctype_d3F5LXplbmhlaQ%2cshadow_50%2ctext_Q1NETiBAQytH%2csize_20%2ccolor_FFFFFF%2ct_70%2cg_se%2cx_16, https://img-blog.csdnimg.cn/7af8a31f83b84f788de290fc40aa0d0e.png?x-oss-process=image/watermark%2ctype_d3F5LXplbmhlaQ%2cshadow_50%2ctext_Q1NETiBAQytH%2csize_20%2ccolor_FFFFFF%2ct_70%2cg_se%2cx_16 1.5x, https://img-blog.csdnimg.cn/7af8a31f83b84f788de290fc40aa0d0e.png?x-oss-process=image/watermark%2ctype_d3F5LXplbmhlaQ%2cshadow_50%2ctext_Q1NETiBAQytH%2csize_20%2ccolor_FFFFFF%2ct_70%2cg_se%2cx_16 2x"
        data-sizes="auto"
        alt="https://img-blog.csdnimg.cn/7af8a31f83b84f788de290fc40aa0d0e.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAQytH,size_20,color_FFFFFF,t_70,g_se,x_16"
        title="https://img-blog.csdnimg.cn/7af8a31f83b84f788de290fc40aa0d0e.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAQytH,size_20,color_FFFFFF,t_70,g_se,x_16" /></p>
<blockquote>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-cpp" data-lang="cpp"><span class="kt">void</span> <span class="nf">wait</span> <span class="p">(</span><span class="n">unique_lock</span><span class="o">&lt;</span><span class="n">mutex</span><span class="o">&gt;&amp;</span> <span class="n">lck</span><span class="p">);</span>
</code></pre></div><p>这是非模板成员函数类型，接收一个unique_lock，调用后，会帮你unlock，并且线程陷入等待状态，直到被调用notify唤醒。</p>
<p>有关notify的成员函数也就这两个：notify_one和notify_all。</p>
<p>顾名思义，随机唤醒一个，和唤醒全部处于等待被唤醒的线程。</p>
</blockquote>
<p>我们再利用新学的条件变量改造下前面的代码如下：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-cpp" data-lang="cpp"><span class="cp">#include</span> <span class="cpf">&lt;iostream&gt;</span><span class="cp">
</span><span class="cp">#include</span> <span class="cpf">&lt;mutex&gt;</span><span class="cp">
</span><span class="cp">#include</span> <span class="cpf">&lt;deque&gt;</span><span class="cp">
</span><span class="cp">#include</span> <span class="cpf">&lt;thread&gt;</span><span class="cp">
</span><span class="cp">#include</span> <span class="cpf">&lt;condition_variable&gt;</span><span class="cp">
</span><span class="cp"></span><span class="n">std</span><span class="o">::</span><span class="n">mutex</span> <span class="n">mtx</span><span class="p">;</span>
<span class="n">std</span><span class="o">::</span><span class="n">deque</span><span class="o">&lt;</span><span class="kt">int</span><span class="o">&gt;</span> <span class="n">q</span><span class="p">;</span>
<span class="n">std</span><span class="o">::</span><span class="n">condition_variable</span> <span class="n">cv</span><span class="p">;</span>

<span class="c1">// producer
</span><span class="c1"></span><span class="kt">void</span> <span class="nf">task1</span><span class="p">(){</span>
    <span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
    <span class="k">while</span> <span class="p">(</span><span class="mi">1</span><span class="p">){</span>
        <span class="n">std</span><span class="o">::</span><span class="n">unique_lock</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">mutex</span><span class="o">&gt;</span> <span class="n">lock</span><span class="p">(</span><span class="n">mtx</span><span class="p">);</span>
        <span class="n">q</span><span class="p">.</span><span class="n">push_back</span><span class="p">(</span><span class="n">i</span><span class="p">);</span>
        <span class="n">cv</span><span class="p">.</span><span class="n">notify_one</span><span class="p">();</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">i</span> <span class="o">&lt;</span> <span class="mi">9999999</span><span class="p">)</span> <span class="p">{</span>
            <span class="n">i</span><span class="o">++</span><span class="p">;</span>
        <span class="p">}</span><span class="k">else</span> <span class="p">{</span>
            <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="c1">// consumer
</span><span class="c1"></span><span class="kt">void</span> <span class="nf">task2</span><span class="p">(){</span>
    <span class="kt">int</span> <span class="n">data</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
    <span class="k">while</span> <span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">std</span><span class="o">::</span><span class="n">unique_lock</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">mutex</span><span class="o">&gt;</span> <span class="n">lock</span><span class="p">(</span><span class="n">mtx</span><span class="p">);</span>
        <span class="k">if</span><span class="p">(</span><span class="n">q</span><span class="p">.</span><span class="n">empty</span><span class="p">())</span> <span class="p">{</span>
            <span class="n">cv</span><span class="p">.</span><span class="n">wait</span><span class="p">(</span><span class="n">lock</span><span class="p">);</span>
        <span class="p">}</span>
        <span class="n">data</span> <span class="o">=</span> <span class="n">q</span><span class="p">.</span><span class="n">front</span><span class="p">();</span>
        <span class="n">q</span><span class="p">.</span><span class="n">pop_front</span><span class="p">();</span>
        <span class="n">std</span><span class="o">::</span><span class="n">cout</span><span class="o">&lt;&lt;</span><span class="s">&#34;Get value from que task2:&#34;</span><span class="o">&lt;&lt;</span><span class="n">data</span><span class="o">&lt;&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="kt">void</span> <span class="nf">task3</span><span class="p">(){</span>
    <span class="kt">int</span> <span class="n">data</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
    <span class="k">while</span> <span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">std</span><span class="o">::</span><span class="n">unique_lock</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">mutex</span><span class="o">&gt;</span> <span class="n">lock</span><span class="p">(</span><span class="n">mtx</span><span class="p">);</span>
        <span class="k">if</span><span class="p">(</span><span class="n">q</span><span class="p">.</span><span class="n">empty</span><span class="p">()){</span>
            <span class="n">cv</span><span class="p">.</span><span class="n">wait</span><span class="p">(</span><span class="n">lock</span><span class="p">);</span>
        <span class="p">}</span>
        <span class="n">data</span> <span class="o">=</span> <span class="n">q</span><span class="p">.</span><span class="n">front</span><span class="p">();</span>
        <span class="n">q</span><span class="p">.</span><span class="n">pop_front</span><span class="p">();</span>
        <span class="n">std</span><span class="o">::</span><span class="n">cout</span><span class="o">&lt;&lt;</span><span class="s">&#34;Get value from que task3:&#34;</span><span class="o">&lt;&lt;</span><span class="n">data</span><span class="o">&lt;&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span>
    <span class="p">}</span>
<span class="p">}</span>


<span class="kt">int</span> <span class="nf">main</span><span class="p">()</span> <span class="p">{</span>
    <span class="n">std</span><span class="o">::</span><span class="kr">thread</span> <span class="n">t1</span><span class="p">(</span><span class="n">task1</span><span class="p">);</span>
    <span class="n">std</span><span class="o">::</span><span class="kr">thread</span> <span class="n">t2</span><span class="p">(</span><span class="n">task2</span><span class="p">);</span>
    <span class="n">std</span><span class="o">::</span><span class="kr">thread</span> <span class="n">t3</span><span class="p">(</span><span class="n">task3</span><span class="p">);</span>
    <span class="n">t1</span><span class="p">.</span><span class="n">join</span><span class="p">();</span>
    <span class="n">t2</span><span class="p">.</span><span class="n">join</span><span class="p">();</span>
    <span class="n">t3</span><span class="p">.</span><span class="n">join</span><span class="p">();</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>

</code></pre></div><h3 id="条件变量引发的虚假唤醒">条件变量引发的虚假唤醒</h3>
<p><strong>什么是虚假唤醒？</strong></p>
<p>前面我们写的利用条件变量写的生产者消费者线程，我可以肯定的告诉你，它是有问题的，运行起来肯定是会报错的！</p>
<p>这是因为虚假唤醒的原因，那么什么是虚假唤醒呢？</p>
<p>虚假唤醒的意思是，当一个正在等待条件变量的线程由于条件变量被触发而唤醒时，却发现它等待的条件（共享数据）没有满足(也就是没有共享数据)。</p>
<p>简而言之就是：明明当前线程已经被唤醒了，却得不到需要的数据。</p>
<p><strong>虚假唤醒的产生分析：</strong></p>
<p>那么我们来分析一下，上面的代码是如何发生的虚假唤醒，如果出现以下情形：task1刚好生成出一个数据到q中，而此时task2被唤醒，把数据读出后又pop掉，然后进入mutex争夺，进入阻塞或者是得到锁，按理来说，只要notify_one真的只会唤醒一个在等待的线程，那么一个生产者对应多个消费者的情况下，是不会产生虚假唤醒的。后面我多番查找资料，说是在多核处理器的环境下，notify_one可能会唤醒不止一个线程，所以会产生一个虚假唤醒，这就导致明明q是空的，却在被读取！</p>
<p><strong>如何避免虚假唤醒？</strong></p>
<p>一个简单粗暴的避免虚假唤醒的法子就是把if语句改为while语句就行，这个产生的直接作用就是，本来唤醒后会因为没有达到预期情况却还往下执行，而while的加入则确保被唤醒的线程一定要是满足预期情况！</p>
<p>代码如下：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-cpp" data-lang="cpp"><span class="cp">#include</span> <span class="cpf">&lt;iostream&gt;</span><span class="cp">
</span><span class="cp">#include</span> <span class="cpf">&lt;mutex&gt;</span><span class="cp">
</span><span class="cp">#include</span> <span class="cpf">&lt;deque&gt;</span><span class="cp">
</span><span class="cp">#include</span> <span class="cpf">&lt;thread&gt;</span><span class="cp">
</span><span class="cp">#include</span> <span class="cpf">&lt;condition_variable&gt;</span><span class="cp">
</span><span class="cp"></span><span class="n">std</span><span class="o">::</span><span class="n">mutex</span> <span class="n">mtx</span><span class="p">;</span>
<span class="n">std</span><span class="o">::</span><span class="n">deque</span><span class="o">&lt;</span><span class="kt">int</span><span class="o">&gt;</span> <span class="n">q</span><span class="p">;</span>
<span class="n">std</span><span class="o">::</span><span class="n">condition_variable</span> <span class="n">cv</span><span class="p">;</span>

<span class="c1">// producer
</span><span class="c1"></span><span class="kt">void</span> <span class="nf">task1</span><span class="p">(){</span>
    <span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
    <span class="k">while</span> <span class="p">(</span><span class="mi">1</span><span class="p">){</span>
        <span class="n">std</span><span class="o">::</span><span class="n">unique_lock</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">mutex</span><span class="o">&gt;</span> <span class="n">lock</span><span class="p">(</span><span class="n">mtx</span><span class="p">);</span>
        <span class="n">q</span><span class="p">.</span><span class="n">push_back</span><span class="p">(</span><span class="n">i</span><span class="p">);</span>
        <span class="n">cv</span><span class="p">.</span><span class="n">notify_one</span><span class="p">();</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">i</span> <span class="o">&lt;</span> <span class="mi">9999999</span><span class="p">)</span> <span class="p">{</span>
            <span class="n">i</span><span class="o">++</span><span class="p">;</span>
        <span class="p">}</span><span class="k">else</span> <span class="p">{</span>
            <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="c1">// consumer
</span><span class="c1"></span><span class="kt">void</span> <span class="nf">task2</span><span class="p">(){</span>
    <span class="kt">int</span> <span class="n">data</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
    <span class="k">while</span> <span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">std</span><span class="o">::</span><span class="n">unique_lock</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">mutex</span><span class="o">&gt;</span> <span class="n">lock</span><span class="p">(</span><span class="n">mtx</span><span class="p">);</span>
        <span class="k">while</span> <span class="p">(</span><span class="n">q</span><span class="p">.</span><span class="n">empty</span><span class="p">())</span> <span class="p">{</span>
            <span class="n">cv</span><span class="p">.</span><span class="n">wait</span><span class="p">(</span><span class="n">lock</span><span class="p">);</span>
        <span class="p">}</span>
        <span class="n">data</span> <span class="o">=</span> <span class="n">q</span><span class="p">.</span><span class="n">front</span><span class="p">();</span>
        <span class="n">q</span><span class="p">.</span><span class="n">pop_front</span><span class="p">();</span>
        <span class="n">std</span><span class="o">::</span><span class="n">cout</span><span class="o">&lt;&lt;</span><span class="s">&#34;Get value from que task2:&#34;</span><span class="o">&lt;&lt;</span><span class="n">data</span><span class="o">&lt;&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="kt">void</span> <span class="nf">task3</span><span class="p">(){</span>
    <span class="kt">int</span> <span class="n">data</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
    <span class="k">while</span> <span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">std</span><span class="o">::</span><span class="n">unique_lock</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">mutex</span><span class="o">&gt;</span> <span class="n">lock</span><span class="p">(</span><span class="n">mtx</span><span class="p">);</span>
        <span class="k">while</span> <span class="p">(</span><span class="n">q</span><span class="p">.</span><span class="n">empty</span><span class="p">()){</span>
            <span class="n">cv</span><span class="p">.</span><span class="n">wait</span><span class="p">(</span><span class="n">lock</span><span class="p">);</span>
        <span class="p">}</span>
        <span class="n">data</span> <span class="o">=</span> <span class="n">q</span><span class="p">.</span><span class="n">front</span><span class="p">();</span>
        <span class="n">q</span><span class="p">.</span><span class="n">pop_front</span><span class="p">();</span>
        <span class="n">std</span><span class="o">::</span><span class="n">cout</span><span class="o">&lt;&lt;</span><span class="s">&#34;Get value from que task3:&#34;</span><span class="o">&lt;&lt;</span><span class="n">data</span><span class="o">&lt;&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span>
    <span class="p">}</span>
<span class="p">}</span>


<span class="kt">int</span> <span class="nf">main</span><span class="p">()</span> <span class="p">{</span>
    <span class="n">std</span><span class="o">::</span><span class="kr">thread</span> <span class="n">t1</span><span class="p">(</span><span class="n">task1</span><span class="p">);</span>
    <span class="n">std</span><span class="o">::</span><span class="kr">thread</span> <span class="n">t2</span><span class="p">(</span><span class="n">task2</span><span class="p">);</span>
    <span class="n">std</span><span class="o">::</span><span class="kr">thread</span> <span class="n">t3</span><span class="p">(</span><span class="n">task3</span><span class="p">);</span>
    <span class="n">t1</span><span class="p">.</span><span class="n">join</span><span class="p">();</span>
    <span class="n">t2</span><span class="p">.</span><span class="n">join</span><span class="p">();</span>
    <span class="n">t3</span><span class="p">.</span><span class="n">join</span><span class="p">();</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div><h2 id="信号量c20">信号量(C++20)</h2>
<p><strong>定义于头文件</strong> <code>&lt;semaphore&gt;</code></p>
<p>信号量是C++20正式加入标准库的，之前使用信号量都是直接调用Linux或者window的底层API，没有统一的接口。</p>
<p>信号量应该算是操作系统里面的一个概念。</p>
<blockquote>
<p>具体而言：</p>
<p>维基百科：信号量（英语：Semaphore）又称为信号量、旗语，是一个同步对象，用于保持在0至指定最大值之间的一个计数值。当线程完成一次对该semaphore对象的等待（wait）时，该计数值减一；当线程完成一次对semaphore对象的释放（release）时，计数值加一。当计数值为0，则线程等待该semaphore对象不能成功直至该semaphore对象变成signaled状态。semaphore对象的计数值大于0，为signaled状态；计数值等于0，为nonsignaled状态.</p>
</blockquote>
<p>其中，信号量又分为两种：二进制信号量和计数信号量。</p>
<p>对应到C++20里面的semaphore就是：</p>
<p><strong>std::binary_semaphore</strong> 和 <strong>counting_semaphore</strong></p>
<h3 id="stdbinary_semaphore使用">std::binary_semaphore使用</h3>
<p>其实binary_semaphore就是counting_sesmaphore的一个特化而已。</p>
<p>定义如下：</p>
<p><code>using binary_semaphore = std::counting_semaphore&lt;1&gt;;</code></p>
<p>讲信号量使用前，我们需要讲讲它的基本运用场景，它一般不使用在存在资源竞争的多线程情况下，比如之前的生产者消费者线程，用信号量是非常不适合的。</p>
<p>比较适合的情况是：某些线程需要在满足某个情况后被通知执行，有点类似于Qt的信号槽机制。</p>
<p>以下有个使用示例：</p>
<blockquote>
<p>以下代码已经还有充分的注释了，具体而言就是可以通过release方法让计数器+1，从而使得信号量状态发生改变，由于binary_semaphore只有0和1两个状态，当状态为1的时候，会使得被阻塞的线程激活，而被激活后会立马把状态-1为0，使得其他线程还是被阻塞状态，所以binary的信号量只能通知一个线程执行任务。</p>
</blockquote>
<p>以下代码定义了两个信号量，一个是从main线程传递到子线程的信号量，一个是从子线程传递到main线程的信号量。</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-cpp" data-lang="cpp"><span class="cp">#include</span> <span class="cpf">&lt;iostream&gt;</span><span class="cp">
</span><span class="cp">#include</span> <span class="cpf">&lt;thread&gt;</span><span class="cp">
</span><span class="cp">#include</span> <span class="cpf">&lt;chrono&gt;</span><span class="cp">
</span><span class="cp">#include</span> <span class="cpf">&lt;semaphore&gt;</span><span class="cp">
</span><span class="cp"></span>

<span class="c1">// global binary semaphore instances
</span><span class="c1">// object counts are set to zero
</span><span class="c1">// objects are in non-signaled state
</span><span class="c1"></span><span class="n">std</span><span class="o">::</span><span class="n">binary_semaphore</span>
        <span class="n">smphSignalMainToThread</span><span class="p">{</span><span class="mi">0</span><span class="p">},</span>
        <span class="n">smphSignalThreadToMain</span><span class="p">{</span><span class="mi">0</span><span class="p">};</span>

<span class="kt">void</span> <span class="nf">ThreadProc</span><span class="p">()</span>
<span class="p">{</span>
    <span class="c1">// wait for a signal from the main proc
</span><span class="c1"></span>    <span class="c1">// by attempting to decrement the semaphore
</span><span class="c1"></span>    <span class="n">smphSignalMainToThread</span><span class="p">.</span><span class="n">acquire</span><span class="p">();</span>

    <span class="c1">// this call blocks until the semaphore&#39;s count
</span><span class="c1"></span>    <span class="c1">// is increased from the main proc
</span><span class="c1"></span>
    <span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;[thread] Got the signal</span><span class="se">\n</span><span class="s">&#34;</span><span class="p">;</span> <span class="c1">// response message
</span><span class="c1"></span>
    <span class="c1">// wait for 3 seconds to imitate some work
</span><span class="c1"></span>    <span class="c1">// being done by the thread
</span><span class="c1"></span>    <span class="k">using</span> <span class="k">namespace</span> <span class="n">std</span><span class="o">::</span><span class="n">literals</span><span class="p">;</span>
    <span class="n">std</span><span class="o">::</span><span class="n">this_thread</span><span class="o">::</span><span class="n">sleep_for</span><span class="p">(</span><span class="mi">3</span><span class="n">s</span><span class="p">);</span>

    <span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;[thread] Send the signal</span><span class="se">\n</span><span class="s">&#34;</span><span class="p">;</span> <span class="c1">// message
</span><span class="c1"></span>
    <span class="c1">// signal the main proc back
</span><span class="c1"></span>    <span class="n">smphSignalThreadToMain</span><span class="p">.</span><span class="n">release</span><span class="p">();</span>
<span class="p">}</span>

<span class="kt">int</span> <span class="nf">main</span><span class="p">()</span>
<span class="p">{</span>
    <span class="c1">// create some worker thread
</span><span class="c1"></span>    <span class="n">std</span><span class="o">::</span><span class="kr">thread</span> <span class="n">thrWorker</span><span class="p">(</span><span class="n">ThreadProc</span><span class="p">);</span>

    <span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;[main] Send the signal</span><span class="se">\n</span><span class="s">&#34;</span><span class="p">;</span> <span class="c1">// message
</span><span class="c1"></span>
    <span class="c1">// signal the worker thread to start working
</span><span class="c1"></span>    <span class="c1">// by increasing the semaphore&#39;s count
</span><span class="c1"></span>    <span class="n">smphSignalMainToThread</span><span class="p">.</span><span class="n">release</span><span class="p">();</span>

    <span class="c1">// wait until the worker thread is done doing the work
</span><span class="c1"></span>    <span class="c1">// by attempting to decrement the semaphore&#39;s count
</span><span class="c1"></span>    <span class="n">smphSignalThreadToMain</span><span class="p">.</span><span class="n">acquire</span><span class="p">();</span>

    <span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;[main] Got the signal</span><span class="se">\n</span><span class="s">&#34;</span><span class="p">;</span> <span class="c1">// response message
</span><span class="c1"></span>    <span class="n">thrWorker</span><span class="p">.</span><span class="n">join</span><span class="p">();</span>
<span class="p">}</span>
</code></pre></div><h3 id="counting_semaphore使用">counting_semaphore使用</h3>
<p>原理与binary版本完全一致只是状态不只是0和1，它能够自定义上限的状态，如下代码，我将上限定为了3，那么release调用的时候可以设置最多+3，那么它就能成功唤醒三个线程.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-cpp" data-lang="cpp"><span class="cp">#include</span> <span class="cpf">&lt;iostream&gt;</span><span class="cp">
</span><span class="cp">#include</span> <span class="cpf">&lt;thread&gt;</span><span class="cp">
</span><span class="cp">#include</span> <span class="cpf">&lt;chrono&gt;</span><span class="cp">
</span><span class="cp">#include</span> <span class="cpf">&lt;semaphore&gt;</span><span class="cp">
</span><span class="cp"></span>

<span class="c1">// global binary semaphore instances
</span><span class="c1">// object counts are set to zero
</span><span class="c1">// objects are in non-signaled state
</span><span class="c1"></span><span class="n">std</span><span class="o">::</span><span class="n">counting_semaphore</span><span class="o">&lt;</span><span class="mi">3</span><span class="o">&gt;</span>
        <span class="n">smphSignalMainToThread</span><span class="p">{</span><span class="mi">0</span><span class="p">},</span>
        <span class="n">smphSignalThreadToMain</span><span class="p">{</span><span class="mi">0</span><span class="p">};</span>
<span class="kt">void</span> <span class="nf">ThreadProc2</span><span class="p">()</span>
<span class="p">{</span>
    <span class="c1">// wait for a signal from the main proc
</span><span class="c1"></span>    <span class="c1">// by attempting to decrement the semaphore
</span><span class="c1"></span>    <span class="n">smphSignalMainToThread</span><span class="p">.</span><span class="n">acquire</span><span class="p">();</span>

    <span class="c1">// this call blocks until the semaphore&#39;s count
</span><span class="c1"></span>    <span class="c1">// is increased from the main proc
</span><span class="c1"></span>
    <span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;[thread] Got the signal2</span><span class="se">\n</span><span class="s">&#34;</span><span class="p">;</span> <span class="c1">// response message
</span><span class="c1"></span>
    <span class="c1">// wait for 3 seconds to imitate some work
</span><span class="c1"></span>    <span class="c1">// being done by the thread
</span><span class="c1"></span>    <span class="k">using</span> <span class="k">namespace</span> <span class="n">std</span><span class="o">::</span><span class="n">literals</span><span class="p">;</span>
    <span class="n">std</span><span class="o">::</span><span class="n">this_thread</span><span class="o">::</span><span class="n">sleep_for</span><span class="p">(</span><span class="mi">3</span><span class="n">s</span><span class="p">);</span>

    <span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;[thread] Send the signal2</span><span class="se">\n</span><span class="s">&#34;</span><span class="p">;</span> <span class="c1">// message
</span><span class="c1"></span>
    <span class="c1">// signal the main proc back
</span><span class="c1"></span>    <span class="n">smphSignalThreadToMain</span><span class="p">.</span><span class="n">release</span><span class="p">();</span>
<span class="p">}</span>

<span class="kt">void</span> <span class="nf">ThreadProc1</span><span class="p">()</span>
<span class="p">{</span>
    <span class="c1">// wait for a signal from the main proc
</span><span class="c1"></span>    <span class="c1">// by attempting to decrement the semaphore
</span><span class="c1"></span>    <span class="n">smphSignalMainToThread</span><span class="p">.</span><span class="n">acquire</span><span class="p">();</span>

    <span class="c1">// this call blocks until the semaphore&#39;s count
</span><span class="c1"></span>    <span class="c1">// is increased from the main proc
</span><span class="c1"></span>
    <span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;[thread] Got the signal1</span><span class="se">\n</span><span class="s">&#34;</span><span class="p">;</span> <span class="c1">// response message
</span><span class="c1"></span>
    <span class="c1">// wait for 3 seconds to imitate some work
</span><span class="c1"></span>    <span class="c1">// being done by the thread
</span><span class="c1"></span>    <span class="k">using</span> <span class="k">namespace</span> <span class="n">std</span><span class="o">::</span><span class="n">literals</span><span class="p">;</span>
    <span class="n">std</span><span class="o">::</span><span class="n">this_thread</span><span class="o">::</span><span class="n">sleep_for</span><span class="p">(</span><span class="mi">3</span><span class="n">s</span><span class="p">);</span>

    <span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;[thread] Send the signal1</span><span class="se">\n</span><span class="s">&#34;</span><span class="p">;</span> <span class="c1">// message
</span><span class="c1"></span>
    <span class="c1">// signal the main proc back
</span><span class="c1"></span>    <span class="n">smphSignalThreadToMain</span><span class="p">.</span><span class="n">release</span><span class="p">();</span>
<span class="p">}</span>

<span class="kt">void</span> <span class="nf">ThreadProc3</span><span class="p">()</span>
<span class="p">{</span>
    <span class="c1">// wait for a signal from the main proc
</span><span class="c1"></span>    <span class="c1">// by attempting to decrement the semaphore
</span><span class="c1"></span>    <span class="n">smphSignalMainToThread</span><span class="p">.</span><span class="n">acquire</span><span class="p">();</span>

    <span class="c1">// this call blocks until the semaphore&#39;s count
</span><span class="c1"></span>    <span class="c1">// is increased from the main proc
</span><span class="c1"></span>
    <span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;[thread] Got the signal3</span><span class="se">\n</span><span class="s">&#34;</span><span class="p">;</span> <span class="c1">// response message
</span><span class="c1"></span>
    <span class="c1">// wait for 3 seconds to imitate some work
</span><span class="c1"></span>    <span class="c1">// being done by the thread
</span><span class="c1"></span>    <span class="k">using</span> <span class="k">namespace</span> <span class="n">std</span><span class="o">::</span><span class="n">literals</span><span class="p">;</span>
    <span class="n">std</span><span class="o">::</span><span class="n">this_thread</span><span class="o">::</span><span class="n">sleep_for</span><span class="p">(</span><span class="mi">3</span><span class="n">s</span><span class="p">);</span>

    <span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;[thread] Send the signal3</span><span class="se">\n</span><span class="s">&#34;</span><span class="p">;</span> <span class="c1">// message
</span><span class="c1"></span>
    <span class="c1">// signal the main proc back
</span><span class="c1"></span>    <span class="n">smphSignalThreadToMain</span><span class="p">.</span><span class="n">release</span><span class="p">();</span>
<span class="p">}</span>

<span class="kt">int</span> <span class="nf">main</span><span class="p">()</span>
<span class="p">{</span>
    <span class="c1">// create some worker thread
</span><span class="c1"></span>    <span class="n">std</span><span class="o">::</span><span class="kr">thread</span> <span class="n">thrWorker1</span><span class="p">(</span><span class="n">ThreadProc1</span><span class="p">);</span>
    <span class="n">std</span><span class="o">::</span><span class="kr">thread</span> <span class="n">thrWorker2</span><span class="p">(</span><span class="n">ThreadProc2</span><span class="p">);</span>

    <span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;[main] Send the signal</span><span class="se">\n</span><span class="s">&#34;</span><span class="p">;</span> <span class="c1">// message
</span><span class="c1"></span>
    <span class="c1">// signal the worker thread to start working
</span><span class="c1"></span>    <span class="c1">// by increasing the semaphore&#39;s count
</span><span class="c1"></span>    <span class="n">smphSignalMainToThread</span><span class="p">.</span><span class="n">release</span><span class="p">(</span><span class="mi">3</span><span class="p">);</span>

    <span class="c1">// wait until the worker thread is done doing the work
</span><span class="c1"></span>    <span class="c1">// by attempting to decrement the semaphore&#39;s count
</span><span class="c1"></span>    <span class="n">smphSignalThreadToMain</span><span class="p">.</span><span class="n">acquire</span><span class="p">();</span>

    <span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;[main] Got the signal</span><span class="se">\n</span><span class="s">&#34;</span><span class="p">;</span> <span class="c1">// response message
</span><span class="c1"></span>    <span class="n">thrWorker1</span><span class="p">.</span><span class="n">join</span><span class="p">();</span>
    <span class="n">thrWorker2</span><span class="p">.</span><span class="n">join</span><span class="p">();</span>
<span class="p">}</span>
</code></pre></div></div><div class="post-footer" id="post-footer">
    <div class="post-info"><div class="post-info-tag"><span><a href="/tags/1.3-%E5%A4%9A%E7%BA%BF%E7%A8%8B%E6%8E%A7%E5%88%B6%E7%9A%84%E5%8F%A6%E4%B8%80%E7%A7%8D%E5%A7%BF%E5%8A%BF-%E6%9D%A1%E4%BB%B6%E5%8F%98%E9%87%8Fcondition_variable-%E4%BF%A1%E5%8F%B7%E9%87%8Fsemaphore/">1.3-多线程控制的另一种姿势-条件变量(condition_variable), 信号量(semaphore)</a>
                </span></div><div class="post-info-line"><div class="post-info-mod">
                <span>更新于 2022-03-27</span>
            </div><div class="post-info-mod"></div>
        </div><div class="post-info-share">
            <span><a href="javascript:void(0);" title="分享到 Twitter" data-sharer="twitter" data-url="https://acking-you.github.io/posts/1.3-%E9%94%81%E9%87%8A%E6%94%BE%E7%9A%84%E5%8F%A6%E4%B8%80%E7%A7%8D%E5%A7%BF%E5%8A%BF-%E6%9D%A1%E4%BB%B6%E5%8F%98%E9%87%8Fcondition_variable-%E4%BF%A1%E5%8F%B7%E9%87%8Fsemaphore/" data-title="1.3-多线程控制的另一种姿势-条件变量(condition_variable), 信号量(semaphore)" data-hashtags="1.3-多线程控制的另一种姿势-条件变量(condition_variable), 信号量(semaphore)"><i class="fab fa-twitter fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Facebook" data-sharer="facebook" data-url="https://acking-you.github.io/posts/1.3-%E9%94%81%E9%87%8A%E6%94%BE%E7%9A%84%E5%8F%A6%E4%B8%80%E7%A7%8D%E5%A7%BF%E5%8A%BF-%E6%9D%A1%E4%BB%B6%E5%8F%98%E9%87%8Fcondition_variable-%E4%BF%A1%E5%8F%B7%E9%87%8Fsemaphore/" data-hashtag="1.3-多线程控制的另一种姿势-条件变量(condition_variable), 信号量(semaphore)"><i class="fab fa-facebook-square fa-fw"></i></a><a href="javascript:void(0);" title="分享到 WhatsApp" data-sharer="whatsapp" data-url="https://acking-you.github.io/posts/1.3-%E9%94%81%E9%87%8A%E6%94%BE%E7%9A%84%E5%8F%A6%E4%B8%80%E7%A7%8D%E5%A7%BF%E5%8A%BF-%E6%9D%A1%E4%BB%B6%E5%8F%98%E9%87%8Fcondition_variable-%E4%BF%A1%E5%8F%B7%E9%87%8Fsemaphore/" data-title="1.3-多线程控制的另一种姿势-条件变量(condition_variable), 信号量(semaphore)" data-web><i class="fab fa-whatsapp fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Line" data-sharer="line" data-url="https://acking-you.github.io/posts/1.3-%E9%94%81%E9%87%8A%E6%94%BE%E7%9A%84%E5%8F%A6%E4%B8%80%E7%A7%8D%E5%A7%BF%E5%8A%BF-%E6%9D%A1%E4%BB%B6%E5%8F%98%E9%87%8Fcondition_variable-%E4%BF%A1%E5%8F%B7%E9%87%8Fsemaphore/" data-title="1.3-多线程控制的另一种姿势-条件变量(condition_variable), 信号量(semaphore)"><i class="fab fa-line fa-fw"></i></a><a href="javascript:void(0);" title="分享到 微博" data-sharer="weibo" data-url="https://acking-you.github.io/posts/1.3-%E9%94%81%E9%87%8A%E6%94%BE%E7%9A%84%E5%8F%A6%E4%B8%80%E7%A7%8D%E5%A7%BF%E5%8A%BF-%E6%9D%A1%E4%BB%B6%E5%8F%98%E9%87%8Fcondition_variable-%E4%BF%A1%E5%8F%B7%E9%87%8Fsemaphore/" data-title="1.3-多线程控制的另一种姿势-条件变量(condition_variable), 信号量(semaphore)" data-image="https://img-blog.csdnimg.cn/img_convert/385f4cc39feda8590ef42f86b38207ba.png#pic_center"><i class="fab fa-weibo fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Myspace" data-sharer="myspace" data-url="https://acking-you.github.io/posts/1.3-%E9%94%81%E9%87%8A%E6%94%BE%E7%9A%84%E5%8F%A6%E4%B8%80%E7%A7%8D%E5%A7%BF%E5%8A%BF-%E6%9D%A1%E4%BB%B6%E5%8F%98%E9%87%8Fcondition_variable-%E4%BF%A1%E5%8F%B7%E9%87%8Fsemaphore/" data-title="1.3-多线程控制的另一种姿势-条件变量(condition_variable), 信号量(semaphore)" data-description="1.3-多线程控制的另一种姿势-条件变量(condition_variable), 信号量(semaphore)"><i data-svg-src="/lib/simple-icons/icons/myspace.min.svg"></i></a><a href="javascript:void(0);" title="分享到 Blogger" data-sharer="blogger" data-url="https://acking-you.github.io/posts/1.3-%E9%94%81%E9%87%8A%E6%94%BE%E7%9A%84%E5%8F%A6%E4%B8%80%E7%A7%8D%E5%A7%BF%E5%8A%BF-%E6%9D%A1%E4%BB%B6%E5%8F%98%E9%87%8Fcondition_variable-%E4%BF%A1%E5%8F%B7%E9%87%8Fsemaphore/" data-title="1.3-多线程控制的另一种姿势-条件变量(condition_variable), 信号量(semaphore)" data-description="1.3-多线程控制的另一种姿势-条件变量(condition_variable), 信号量(semaphore)"><i class="fab fa-blogger fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Evernote" data-sharer="evernote" data-url="https://acking-you.github.io/posts/1.3-%E9%94%81%E9%87%8A%E6%94%BE%E7%9A%84%E5%8F%A6%E4%B8%80%E7%A7%8D%E5%A7%BF%E5%8A%BF-%E6%9D%A1%E4%BB%B6%E5%8F%98%E9%87%8Fcondition_variable-%E4%BF%A1%E5%8F%B7%E9%87%8Fsemaphore/" data-title="1.3-多线程控制的另一种姿势-条件变量(condition_variable), 信号量(semaphore)"><i class="fab fa-evernote fa-fw"></i></a></span>
        </div></div><div class="post-nav"><a href="/posts/%E5%88%A9%E7%94%A8string_view%E4%BC%98%E5%8C%96%E7%8E%B0%E4%BB%A3c&#43;&#43;%E8%AF%AD%E6%B3%95/" class="prev" rel="prev" title=""><i class="fas fa-angle-left fa-fw"></i>Previous Post</a>
            <a href="/posts/%E5%AE%9E%E7%8E%B0%E5%AE%9E%E6%97%B6qq%E5%A5%BD%E5%8F%8B%E6%90%9C%E7%B4%A2%E6%A1%86/" class="next" rel="next" title="实现实时qq好友搜索框">Next Post<i class="fas fa-angle-right fa-fw"></i></a></div></div>
</div></article></div>
            </main>
            <footer class="footer"><div class="footer-container"><div class="footer-line">由 <a href="https://gohugo.io/" target="_blank" rel="noopener noreffer" title="Hugo 0.86.0">Hugo</a> 强力驱动 | 主题 - <a href="https://github.com/khusika/FeelIt" target="_blank" rel="noopener noreffer" title="FeelIt 1.0.1"><i class="fas fa-hand-holding-heart fa-fw"></i> FeelIt</a>
        </div><div class="footer-line" itemscope itemtype="http://schema.org/CreativeWork"><i class="far fa-copyright fa-fw"></i><span itemprop="copyrightYear">2023</span><span class="author" itemprop="copyrightHolder">&nbsp;<a href="/"></a></span></div>
</div>
</footer>
        </div>

        <div id="fixed-buttons"><a href="#" id="back-to-top" class="fixed-button" title="回到顶部">
                <i class="fas fa-chevron-up fa-fw"></i>
            </a></div><link rel="stylesheet" href="/lib/fontawesome-free/all.min.css"><link rel="stylesheet" href="/lib/animate/animate.min.css"><link rel="stylesheet" href="/lib/katex/katex.min.css"><link rel="stylesheet" href="/lib/katex/copy-tex.min.css"><script src="/lib/autocomplete/autocomplete.min.js"></script><script src="/lib/lunr/lunr.min.js"></script><script src="/lib/lunr/lunr.stemmer.support.min.js"></script><script src="/lib/lunr/lunr.zh.min.js"></script><script src="/lib/lazysizes/lazysizes.min.js"></script><script src="/lib/clipboard/clipboard.min.js"></script><script src="/lib/sharer/sharer.min.js"></script><script src="/lib/katex/katex.min.js"></script><script src="/lib/katex/auto-render.min.js"></script><script src="/lib/katex/copy-tex.min.js"></script><script src="/lib/katex/mhchem.min.js"></script><script>window.config={"code":{"copyTitle":"复制到剪贴板","maxShownLines":200},"comment":{},"math":{"delimiters":[{"display":true,"left":"$$","right":"$$"},{"display":true,"left":"\\[","right":"\\]"},{"display":false,"left":"$","right":"$"},{"display":false,"left":"\\(","right":"\\)"}],"strict":false},"search":{"highlightTag":"em","lunrIndexURL":"/index.json","lunrLanguageCode":"zh","lunrSegmentitURL":"/lib/lunr/lunr.segmentit.js","maxResultLength":100,"noResultsFound":"没有找到结果","snippetLength":50,"type":"lunr"}};</script><script src="/js/theme.min.js"></script></body></html>
